package com.ujs.listnode.code.RemoveNode;

import com.ujs.listnode.code.ListNode;

/**
 * @author zhangshihao
 * @create 2023-09-26 16:21
 */
public class MyLinkedList {
    public static void main(String[] args) {
        MyLinkedList myLinkedList = new MyLinkedList();
        myLinkedList.addAtHead(7);
        myLinkedList.addAtHead(2);
        myLinkedList.addAtHead(1);
        myLinkedList.addAtIndex(3, 0);
        for (int i = 0; i < myLinkedList.size; i++) {
            System.out.print(myLinkedList.get(i) + " ");
        }
        myLinkedList.deleteAtIndex(2);
        myLinkedList.addAtHead(6);
        myLinkedList.addAtTail(4);
        int i1 = myLinkedList.get(4);
        myLinkedList.addAtHead(4);
        myLinkedList.addAtIndex(5, 0);
        myLinkedList.addAtHead(6);
        // for (int i = 0; i < myLinkedList.size; i++) {
        //     System.out.print(myLinkedList.get(i) + " ");
        // }
        // System.out.println();
        // myLinkedList.deleteAtIndex(1);
        // for (int i = 0; i < myLinkedList.size; i++) {
        //     System.out.print(myLinkedList.get(i) + " ");
        // }
    }

    public int size = 0;
    public ListNode head;

    public MyLinkedList() {
        // 链表的长度
        size = 0;
        // 虚拟头结点
        head = new ListNode(0);
    }

    public int get(int index) {
        if (index >= size || index < 0) {
            return -1;
        }
        ListNode currentNode = head;
        for (int i = 0; i <= index; i++) {
            currentNode = currentNode.next;
        }
        return currentNode.val;
    }

    public void addAtHead(int val) {
        addAtIndex(0, val);
    }

    public void addAtTail(int val) {
        addAtIndex(size, val);
    }

    public void addAtIndex(int index, int val) {
        if (index > size) {
            return;
        }
        if (index < 0) {
            index = 0;
        }
        size++;
        // 要插入的位置之前的节点。
        ListNode preNode = head;
        for (int i = 0; i < index; i++) {
            preNode = preNode.next;
        }
        ListNode toAdd = new ListNode(val);
        toAdd.next = preNode.next;
        preNode.next = toAdd;
    }

    public void deleteAtIndex(int index) {
        if (index < 0 || index >= size) {
            return;
        }
        size--;
        ListNode pre = head;
        for (int i = 0; i < index; i++) {
            pre = pre.next;
        }
        pre.next = pre.next.next;
    }
}
